package com.smart.fourteen.hibernate.base.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

@Transactional() //子类dao想要使用事务，需要父类BaseDao层加上@Transactional注解。子类也需加上注解
public class BaseDao<T> {
    @Autowired
    private HibernateTemplate hibernateTemplate;

    private Class entityClass;

    public BaseDao() {
        //获取泛型的entityClass
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class) params[0];
    }

    public T get(Serializable id){
        return (T) hibernateTemplate.get(entityClass, id);
    }

    public void save(T entity){
        hibernateTemplate.save(entity);
    }

    public void update(T entity){
        hibernateTemplate.update(entity);
    }

    public void delete(T entity){
        hibernateTemplate.delete(entity);
    }

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

}
